<!doctype html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Tauri App</title>
</head>

<body>
  <div style="display:flex;justify-content:center;align-items:center;flex-direction:column">
    <img width="200" id="img1" alt="无法打开摄像头"></img>
  </div>
  <script>
    let closeCameraWindow=false
    let init=false
    async function getCameraImg() {
      const { invoke } = window.__TAURI__.core
      return await invoke('get_camera_img');
    }
    
    const img1 = document.getElementById('img1')
    img1.onload = function () {
      //console.log('宽度:', img1.width);
      //console.log('高度:', img1.height);
      const { getCurrentWindow, LogicalSize, Window } = window.__TAURI__.window

      Window.getByLabel('main').then( async (win) => {
        if (!win) {// 如果主窗口已经关闭
          //  console.log(getCurrentWindow().closeCameraWindow)
          closeCameraWindow=true
          getCurrentWindow().close()
        }
        
      })

      getCurrentWindow().setSize(new LogicalSize(250, img1.height + 30));
    }
    async function show(imgData) {
      const blob = new Blob([new Uint8Array(imgData)], { type: 'image/png' });
      const imageUrl = URL.createObjectURL(blob)
      img1.src = imageUrl;
    }
    
    setInterval(async () => {
      
      if (!init && window.__TAURI__) {
        const { getCurrentWindow, LogicalSize, Window } = window.__TAURI__.window
        const wv=getCurrentWindow()
        wv.onCloseRequested(async (event) => {
            //console.log("onclose======closeCameraWindow=%o",event)
            if(!closeCameraWindow){
              event.preventDefault()
            }
            closeCameraWindow=false
        })
        // 监听主动关闭事件
        const unlisten = await wv.listen("closeCameraWindow", e => {
          //console.log("================closeCameraWindow")
          closeCameraWindow=true
          wv.close()
        })
        //unlisten();
        init=true
      }


      let imgData = await getCameraImg().then((imgData) => {
        show(imgData)
      })
    }, 1000);
  </script>
</body>

</html>